package com.multiplepb.application;

import com.multiplepb.MultiplepbApplication;
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.stage.Stage;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

import static org.springframework.boot.WebApplicationType.NONE;

/**
 * @author 单耀
 * @date 2025/1/25 17:37
 */
public class PbPlatformApplication extends Application {
    private ConfigurableApplicationContext applicationContext;
    @Override
    public void init() {
        applicationContext = new SpringApplicationBuilder()
                .web(NONE)
                .sources(MultiplepbApplication.class)
                .initializers(newApplicationContextInitializer(this))
                .run(getParameters().getRaw().toArray(new String[0]));
    }

    private static ApplicationContextInitializer<GenericApplicationContext> newApplicationContextInitializer(Application application) {
        return ac -> {
            ac.registerBean(Application.class, () -> application);
            ac.registerBean(Application.Parameters.class, application::getParameters);
            ac.registerBean(HostServices.class, application::getHostServices);
        };
    }
    public static void main(String[] args) {
        launch();
    }
    @Override
    public void start(Stage stage)  {
        applicationContext.publishEvent(new StageReadyEvent(stage));
    }
    public static  class StageReadyEvent extends ApplicationEvent {

        public StageReadyEvent(Stage stage) {
            super(stage);
        }

        public Stage getStage() {
            return (Stage) getSource();
        }
    }
}
